#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/6/10 16:13
# @Author : linjinting
# @Project : custom_protocol
# @File : custom_widget.py
# @Software: PyCharm

from PySide2 import QtWidgets
from PySide2.QtCore import Signal, Qt
# from PySide2.QtGui import QMouseEvent


class CustomLineEdit(QtWidgets.QLineEdit):
    clicked = Signal()

    def mouseReleaseEvent(self, _QMouseEvent):
        if _QMouseEvent.button() == Qt.LeftButton:
            self.clicked.emit()


class ComboCheckBox(QtWidgets.QComboBox):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.m_items = ({'ID': 0, 'name': '全选'.encode()},)
        self.box_list = list()
        self.deviceTypeID = list()
        self.state = 0
        self.m_QList = QtWidgets.QListWidget()
        self.m_text_widgets = CustomLineEdit()
        self.m_text_widgets.setReadOnly(True)
        self.m_text_widgets.clicked.connect(self.showPopup)
        self.setLineEdit(self.m_text_widgets)
        self.setModel(self.m_QList.model())
        self.setView(self.m_QList)

    def add_items(self, items):
        self.m_items = self.m_items + items
        self.init_items()

    def init_items(self):
        self.box_list = list()
        self.deviceTypeID = list()
        self.m_QList.clear()

        for i in range(len(self.m_items)):
            checkBox = QtWidgets.QCheckBox()
            # tt = self.m_items
            # print(tt)
            checkBox.setText(self.m_items[i]['name'].decode())
            self.box_list.append(checkBox)
            item = QtWidgets.QListWidgetItem(self.m_QList)
            item.setData(0, self.m_items[i])
            self.m_QList.setItemWidget(item, self.box_list[i])

            if i == 0:
                self.box_list[i].stateChanged.connect(self.all_selected)
            else:
                self.box_list[i].stateChanged.connect(self.show_selected)

    def all_selected(self):
        if self.state == 0:
            self.state = 1
            for i in range(1, len(self.m_items)):
                self.box_list[i].setChecked(True)
        else:
            self.state = 0
            for i in range(1, len(self.m_items)):
                self.box_list[i].setChecked(False)
        self.show_selected()

    def get_selected(self):
        ret = list()
        for i in range(1, len(self.m_items)):
            if self.box_list[i].isChecked():
                ret.append(self.box_list[i].text())
                self.deviceTypeID.append(self.m_QList.item(i).data(0)['ID'])
        return ret

    def show_selected(self):
        self.m_text_widgets.clear()
        ret = ';'.join(self.get_selected())
        self.m_text_widgets.setText(ret)

    # def e_event(self, text):
    #     print(text)